import { ref } from 'vue'

export interface CopyToastOptions {
  message: string
  type: 'success' | 'error'
  duration?: number
}

// 使用shallowRef来避免深度响应式，提高性能
const toastComponent = ref<ReturnType<typeof createToastComponent> | null>(null)
let debounceTimer: number | null = null

function createToastComponent(options: CopyToastOptions) {
  return {
    id: `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    ...options,
  }
}

export function useCopyToast() {
  const showToast = (options: CopyToastOptions) => {
    // 防抖机制：清除之前的定时器
    if (debounceTimer) {
      clearTimeout(debounceTimer)
      debounceTimer = null
    }

    // 如果已经有toast显示，先清除它
    if (toastComponent.value) {
      toastComponent.value = null
      // 等待一个tick再显示新的toast，确保动画正确
      setTimeout(() => {
        displayToast(options)
      }, 50)
    } else {
      displayToast(options)
    }
  }

  const displayToast = (options: CopyToastOptions) => {
    toastComponent.value = createToastComponent(options)

    // 设置防抖定时器
    const duration = options.duration || 2000
    debounceTimer = window.setTimeout(() => {
      toastComponent.value = null
      debounceTimer = null
    }, duration)
  }

  const showSuccess = (message: string, duration?: number) => {
    showToast({
      message,
      type: 'success',
      duration,
    })
  }

  const showError = (message: string, duration?: number) => {
    showToast({
      message,
      type: 'error',
      duration,
    })
  }

  const clear = () => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
      debounceTimer = null
    }
    toastComponent.value = null
  }

  return {
    toastComponent,
    showSuccess,
    showError,
    clear,
  }
}
